import {InjectionKey} from 'vue'
import {createStore,Store} from 'vuex'
import persistedState from 'vuex-persistedstate'

interface State{
    userinfo?:UserInfoitf
}
interface UserInfoitf{
    roles:string[],
    username:string,
    menus:Menus[],
    icon:string | null
}
interface Menus{
    createTime: string
    hidden: number
    icon: string | null
    id: number
    level:number
    name: string
    parentId:number
    sort: number
    title: string,
    children?:Menus[]
}
interface menusObj{
    [key:string]:Menus
}
export const key:InjectionKey<Store<State>> = Symbol()
const store = createStore<State>({
    state:{
        userinfo:undefined
    },
    getters:{
        genMenus(state){
            const menus = state.userinfo?.menus
            const newMenus:menusObj = {}
            if(menus){
                for(let i =0;i< menus.length;i++){
                    if(!menus[i].parentId){
                        const mid = menus[i].id
                        if(newMenus[mid]?.children){
                            menus[i].children = newMenus[mid].children
                        }
                        newMenus[mid] = menus[i]
                    }else{
                        const parentId = menus[i].parentId;
                        newMenus[parentId] =  newMenus[parentId]  || {};
                        newMenus[parentId].children =  newMenus[parentId].children  || [];
                        newMenus[parentId].children?.push(menus[i])
                    }
                }
            }
            return newMenus
        }
    },
    mutations:{
        USER(state,userinfo:UserInfoitf){
            state.userinfo = userinfo
        }
    },
    actions:{},
    plugins:[
        persistedState({storage:window.sessionStorage})
    ]

})

export default store